// Functions to initialize tables and tabs when the page is loaded.
$(document).ready(function() {
    $('#tabs').tabs();
    if (document.getElementById("clientTable") !== null){
        createTable("#clientTable");
    }
    if (document.getElementById("labTable") !== null){
        createTable("#labTable");
    }
    if (document.getElementById("userTable") !== null){
        createTable("#userTable");
    }
    if (document.getElementById("eCheckListTable") !== null){
        createTable("#eCheckListTable");
    }
	if (document.getElementById("sCheckListTable") !== null){
        createTable("#sCheckListTable");
    }
    if (document.getElementById("routeTable") !== null){
        createTable("#routeTable");
    }
    if (document.getElementById("adminTable") !== null){
        createTable("#adminTable");
    }
	if (document.getElementById("hospitalTable") !== null){
        createTable("#hospitalTable");
    }
	if (document.getElementById("clientSiteTable") !== null){
        createTable("#clientSiteTable");
    }
	if (document.getElementById("labScan") !== null) {
		$('#labScan').submit(function() {
		return false;
	});
	}
	
	
	
	
	
	
	$.idleTimeout('#idletimeout', '#idletimeout a', {
	//Idle set to be 5 minutes.
	idleAfter: 300,
	warningLength: 60,
	onTimeout: function(){
		$(this).slideUp();
		window.location.reload();
	},
	onIdle: function(){
		$(this).slideDown(); // show the warning bar
	},
	onCountdown: function( counter ){
		$(this).find("span").html( counter ); // update the counter
	},
	onResume: function(){
		$(this).slideUp(); // hide the warning bar
	}
});
});

//Create detail field when the detail icon is click on the table. 
function fnFormatDetails(table, nTr2) {
    var aData = table.fnGetData(nTr2);
    var sOut = '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">';
    sOut += '<tr><td>Specimen:</td><td>' + aData[1] + ' ' + aData[2]
            + '</td></tr>';
    sOut += '<tr><td>Link to source:</td><td>Could provide a link here</td></tr>';
    sOut += '<tr><td>Extra info:</td><td>And any further details here (images etc)</td></tr>';
    sOut += '</table>';

    return sOut;
}

//Validate form input field and display error message if data has empty string.
function ValidateInputBox(textField, displayError) {
	var field = $('input[name=' +textField +']');
	var error = $('span[id=' + displayError +']');
	
	//Trimming string for whitespace.
	field.val(jQuery.trim(field.val()));
	if (field.val() === '')
	{
		//Display Error Icon within the textfield.
		field.addClass('highlight text');
		//DIsplay error message
		error.removeClass('hiddenMessage');
		return false;
	}
	else {
		//Remove Error Icon.
		field.removeClass('highlight text');
		//Remove Error Message
		error.addClass('hiddenMessage');
		return true;
	}
}

//Validate Textarea and display error message if data has empty string.
function ValidateTextareaBox(textField, displayError) {
	var field = $('textarea[name=' +textField +']');
	var error = $('span[id=' + displayError +']');
	
	//Trimming string for whitespace.
	field.val(jQuery.trim(field.val()));
	if (field.val() === '')
	{
		//Display Error Icon within the textfield.
		field.addClass('highlight text');
		//DIsplay error message
		error.removeClass('hiddenMessage');
		return false;
	}
	else {
		//Remove Error Icon.
		field.removeClass('highlight text');
		//Remove Error Message
		error.addClass('hiddenMessage');
		return true;
	}
}
//Validate and display error message if the default option is selected.
function ValidateDropBox(dropField, displayError) {
	var field = $('select[name=' + dropField +'] option:selected');
	var error = $('span[id=' + displayError +']');
	
	if (field.val() === -1)
	{
		//Display Error Icon within the textfield.
		field.addClass('highlight text');
		//DIsplay error message
		error.removeClass('hiddenMessage');
		return false;
	}
	else {
		//Remove Error Icon.
		field.removeClass('highlight text');
		//Remove Error Message
		error.addClass('hiddenMessage');
		return true;
	}
}

// Create Table Instance for advanced javascript datatable.
function createTable(tableName) {
    var oTable;

    // Create Expand (+ symbol) to expand details on items within the table.
    var nCloneTh = document.createElement('th');
	
    var nCloneTd = document.createElement('td');
	
    nCloneTd.innerHTML = '<img src="img/details_open.png" alt="expand"/>';
    nCloneTd.className = "center";
    // Adding an empty column within the header.
    $(tableName + ' thead .trClass').each(function() {
        this.insertBefore(nCloneTh, this.childNodes[0]);
		
    });

    // Adding (+ symbol) to each row.
    $(tableName + ' tbody .trClass').each(function() {
        this.insertBefore(nCloneTd.cloneNode(true), this.childNodes[0]);	
    });

    // Setting table instance with predefinited options.
    oTable = $(tableName).dataTable({
        // Set the page system for the table.
        "sPaginationType" : "full_numbers",
        "bAutoWidth" : false,
        // Set to display "processing" when table is being load.
        "bProcessing" : true,
        "aaSorting" : [ [ 1, 'asc' ] ],
        // Setting the first column to non-sortable.
        /*"aoColumnDefs" : [ {
            "bSortable" : false,
            "aTargets" : [ 0 ]
        }]*/
    });
	$(tableName + ' tbody').click(function(event) {
		$(oTable.fnSettings().aoData).each(function (){
			$(this.nTr).removeClass('row_selected');
		});
		$(event.target.parentNode).addClass('row_selected');
		
	});
	
	
	
    // Add detail box when (+ symbol) is clicked for each row.
    $(tableName + ' tbody td img').live('click', function() {
        var nTr = this.parentNode.parentNode;
        if (this.src.match('details_close')) {
            /* This row is already open - close it */
            this.src = "img/details_open.png";
            oTable.fnClose(nTr);
        } else {
            /* Open this row */
            this.src = "img/details_close.png";
            oTable.fnOpen(nTr, fnFormatDetails(oTable, nTr), 'details');
        }
    });
    // TODO: Make Editing work!
    // Set callback function to process editted data.
    $('.editable', oTable.fnGetNodes()).editable('editable_ajax.php', {
        "callback" : function(sValue, y) {
            var aPos = oTable.fnGetPosition(this);
            oTable.fnUpdate(sValue, aPos[0], aPos[1]);
        },
        "submitdata" : function(value, settings) {
            return {
                "row_id" : this.parentNode.getAttribute('id'),
                "column" : oTable.fnGetPosition(this)[2]
            };
        },
        "height" : "14px"
    });
}

// Function uses to expand and retract form.
function ECForm(formName, linkName, linkOpenText) {
    var form = document.getElementById(formName);
    var oLink = document.getElementById(linkName);

    if (form.style.display === 'none') {
        form.style.display = 'block';
        oLink.innerHTML = '<img src="img/details_close.png" alt="Close"/>Close';
    } else {
        form.style.display = 'none';
        oLink.innerHTML = '<img src="img/details_open.png" alt="Expand"/>'
                + linkOpenText;
    }
}

function fnGetSelected( oTableLocal )
{
	var aReturn = new Array();
	var aTrs = oTableLocal.fnGetNodes();
	
	for ( var i=0 ; i<aTrs.length ; i++ )
	{
		if ( $(aTrs[i]).hasClass('row_selected') )
		{
			aReturn.push( aTrs[i] );
		}
	}
	return aReturn;
}

